package com.atguigu.gmall.payment.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.entity.OrderInfo;
import com.atguigu.gmall.payment.properties.AlipayProperties;
import com.atguigu.gmall.payment.service.AlipayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:lyd
 **/
@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    AlipayClient alipayClient;
    @Autowired
    AlipayProperties alipayProperties;
    @Autowired
    OrderFeignClient orderFeignClient;

    @Override
    public String getPayPage(Long orderId) throws AlipayApiException {
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());

        OrderInfo data = orderFeignClient.getOrderInfoById(orderId).getData();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = data.getOutTradeNo();
        //付款金额，必填
        String total_amount = data.getTotalAmount().toString();
        //订单名称，必填
        String subject = "尚品汇订单：" + data.getTradeBody();
        //商品描述，可空
        String body = data.getTradeBody();
        String product_code = "FAST_INSTANT_TRADE_PAY";
        Map<String, String> map = new HashMap<>();
        map.put("out_trade_no", out_trade_no);
        map.put("total_amount", total_amount);
        map.put("subject", subject);
        map.put("body", body);
        map.put("product_code", product_code);
        //设置订单绝对过期时间 格式为yyyy-MM-dd HH:mm:ss
        Date expireTime = data.getExpireTime();
        map.put("time_expire", DateUtil.formatDate(expireTime, "yyyy-MM-dd HH:mm:ss"));
        String bizJson = JsonUtil.objToJsonStr(map);
        alipayRequest.setBizContent(bizJson);
        //请求； 得到支付宝响应数据
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }
}
